package com.leyou.search.mq;

import com.leyou.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.Queue.SEARCH_ITEM_DOWN;
import static com.leyou.common.constants.MQConstants.Queue.SEARCH_ITEM_UP;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Component
public class ItemListener {

    @Autowired
    private SearchService searchService;

    //1、上架：更新索引
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value=SEARCH_ITEM_UP, durable = "true"),// 定义队列
            exchange = @Exchange(  // 定义交换机
                    value = ITEM_EXCHANGE_NAME,
                    type = ExchangeTypes.TOPIC
            ),
            key = ITEM_UP_KEY  // 绑定routing key
    ))
    public void itemUp(Long spuId){
        if(spuId!=null) {
            searchService.saveGoods(spuId);
        }
    }

    //2、下架：删除索引库
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value=SEARCH_ITEM_DOWN, durable = "true"),// 定义队列
            exchange = @Exchange(  // 定义交换机
                    value = ITEM_EXCHANGE_NAME,
                    type = ExchangeTypes.TOPIC
            ),
            key = ITEM_DOWN_KEY  // 绑定routing key
    ))
    public void itemDown(Long spuId){
        if(spuId != null){
            searchService.deleteGoods(spuId);
        }
    }
}
